package com.xiyi.shouxin.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.xiyi.shouxin.dao.admin.SystemConfigRepository;
import com.xiyi.shouxin.entity.admin.SystemConfig;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.SystemConfigView;

@Service
public class SystemConfigService {
    @Autowired
    private SystemConfigRepository systemConfigRepository;

    public void updateSystemConfig(SystemConfig config) throws CommonException {
        if (config == null || config.getConfigName() == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        systemConfigRepository.updateByConfigName(config.getConfigName(), config);
    }

    public SystemConfigView findSystemConfig(String configName) throws CommonException {
        if (!StringUtils.hasText(configName)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        SystemConfig config=systemConfigRepository.findByConfigName(configName);
        return new SystemConfigView(config);
    }

    public ItemPage<SystemConfigView> findSystemConfigList(String configName, int page, int size)
            throws Exception {
        List<SystemConfigView> list = new ArrayList<>();
        List<SystemConfig> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");

        result = systemConfigRepository.findByMultiConditionsByPage(configName, sort, page, size);
        total = systemConfigRepository.countByMultiConditions(configName);

        for (SystemConfig config : result) {
            list.add(new SystemConfigView(config));
        }
        return new ItemPage<SystemConfigView>(list, total);
    }

}
